﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;
using System.Diagnostics;
using System.IO;

namespace DatabaseLayer
{
    public class DatabaseContextFactory
    {
        static DatabaseContextFactory()
        {

        }

        static readonly string ConnectionStringId = "SpeakupEntities";

        static public SpeakupEntities Create()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(assembly.Location);
            

            ConnectionStringSettings connectionStringSettings = 
                                        cfg.ConnectionStrings.ConnectionStrings[ConnectionStringId];

            if (connectionStringSettings == null)
            {
                if (File.Exists(cfg.FilePath) == false)
                {
                    Trace.TraceError("Failed to locate {0} configuration file: {1}",
                                      Path.GetFileName(assembly.Location), 
                                      cfg.FilePath);
                }
                else
                {
                    Trace.TraceError("{0} configuration file does not have connection string with id \"{1}\"",
                                      Path.GetFileName(cfg.FilePath), 
                                      ConnectionStringId);
                }

                //try to find connection string in current application's configuration file
                connectionStringSettings = ConfigurationManager.ConnectionStrings[ConnectionStringId];                
            }

            if (connectionStringSettings == null)
            {
                throw new FileNotFoundException("Can not load configuration file.",cfg.FilePath);
            }
            
            return new SpeakupEntities(connectionStringSettings.ConnectionString);
        }
    }
}
